import 'dart:io';

import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../../lib_baseview/root_page.dart';
import '../../../../../lib_baseview/widget/dialogs.dart';
import '../../../../../lib_baseview/widget/themes.dart';
import '../../../../../lib_runtime/logger.dart';
import '../../../../../resource/language/generated/l10n.dart';
import '../model/room_music_center_controller.dart';
import '../model/room_music_mine_controller.dart';
import '../widget/music_media_bar_widget.dart';
import 'music_playlist_page.dart';
import 'music_upload_confirm_page.dart';
import 'room_music_search_page.dart';

/// 房间音乐主界面
class RoomMusicPage extends StatefulWidget {
  const RoomMusicPage({super.key});

  @override
  State<StatefulWidget> createState() => RoomMusicPageState();

  static Future? show() {
    Get.put(RoomMusicCenterController(), permanent: true);
    Get.put(RoomMusicMineController());
    return Get.bottomSheet(const RoomMusicPage(),
        settings: const RouteSettings(name: '/RoomMusicPage'),
        enableDrag: false,
        isScrollControlled: true);
  }
}

class RoomMusicPageState extends State<RoomMusicPage>
    with TickerProviderStateMixin {
  late TextEditingController _textController;

  TabController? _tabController;

  late RoomMusicCenterController centerController;

  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _textController = TextEditingController();
    centerController = Get.find<RoomMusicCenterController>();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.bottomCenter,
      child: Column(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () => Get.back(),
            child: Container(
              height: Get.height * 0.2,
              width: Get.width,
            ),
          ),
          Expanded(
            child: Container(
              decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadiusDirectional.only(
                      topStart: Radius.circular(16),
                      topEnd: Radius.circular(16))),
              child: Stack(
                children: [
                  Column(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      const SizedBox(height: 20),
                      Row(
                        children: [
                          const Spacer(),
                          Text(T.current.music,
                              style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600)),
                          Expanded(
                            child: Row(
                              children: [
                                const Spacer(),
                                GestureDetector(
                                  onTap: () {
                                    RLog.d(
                                        'addMusicAction ${appNavigatorObserver.history}');

                                    showRideBottomSheet(context, [
                                      T.current!.local_net_upload,
                                      T.current!.choose_local_music,
                                      T.current!.cancel
                                    ], (context, index) {
                                      switch (index) {
                                        case 0:
                                          // Get.to(() => const WifiScreen(),
                                          //         preventDuplicates: false)
                                          //     ?.whenComplete(() =>
                                          //         Navigator.of(context).pop());
                                          break;
                                        case 1:
                                          _pickMusics();
                                          Navigator.of(context).pop();
                                          break;
                                        case 2:
                                          Navigator.of(context).pop();
                                          break;
                                      }
                                      return const SizedBox.shrink();
                                    });
                                  },
                                  child: Padding(
                                    padding: const EdgeInsetsDirectional.only(
                                        end: 20),
                                    child: Text(
                                      T.current!.add_song,
                                      style: const TextStyle(
                                          color: RColors.buttonYellow,
                                          fontSize: 13,
                                          fontWeight: FontWeight.w600),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          )
                        ],
                      ),
                      const SizedBox(height: 10),
                      searchBar,
                      Expanded(
                        child: PageView(
                          controller: centerController.pageController,
                          physics: const NeverScrollableScrollPhysics(),
                          children: [
                            GetBuilder<RoomMusicCenterController>(
                                builder: (logic) {
                              if (logic.musicCharts == null) {
                                return const Center(
                                    child: CupertinoActivityIndicator());
                              }
                              _tabController ??= TabController(
                                  length: logic.musicCharts!.length,
                                  vsync: this);

                              return Column(
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Container(
                                    height: 30,
                                    padding: const EdgeInsets.only(left: 22),
                                    alignment: AlignmentDirectional.centerStart,
                                    child: TabBar(
                                      tabs: logic.musicCharts!
                                          .map((e) => Tab(text: e.chartName))
                                          .toList(),
                                      controller: _tabController,
                                      isScrollable: true,
                                      padding: EdgeInsets.zero,
                                      labelPadding:
                                          EdgeInsetsDirectional.only(end: 12),
                                      indicatorColor: const Color(0xFFFFD400),
                                      unselectedLabelColor:
                                          const Color(0xFF999999),
                                      labelColor: const Color(0xFF333333),
                                      indicatorSize: TabBarIndicatorSize.tab,
                                      // indicator: const DFUnderlineTabIndicator(
                                      //   borderSide: BorderSide(
                                      //       width: 4.0,
                                      //       color: Color(0xFFFFD400)),
                                      //   raduis: 2,
                                      //   wantWidth: 20,
                                      //   draggingWidth: 4,
                                      // ),
                                      labelStyle: const TextStyle(
                                        color: Color(0xFF333333),
                                        fontWeight: FontWeight.bold,
                                        fontSize: 15,
                                      ),
                                      unselectedLabelStyle: const TextStyle(
                                        color: Color(0xFF999999),
                                        fontWeight: FontWeight.bold,
                                        fontSize: 15,
                                      ),
                                    ),
                                  ),
                                  Text('Expanded'),
                                  // Expanded(
                                  //   child: TabBarView(
                                  //     controller: _tabController,
                                  //     children: logic.musicCharts!
                                  //         .map<Widget>((item) {
                                  //       if (item.id == 0x111) {
                                  //         return KeepAliveWrapper(
                                  //             child:
                                  //                 RoomMusicCollectedPage(item));
                                  //       } else if (item.id == 0x222) {
                                  //         return KeepAliveWrapper(
                                  //             child: RoomMusicMinePage(item));
                                  //       } else {
                                  //         return KeepAliveWrapper(
                                  //             child: RoomMusicListPage(item));
                                  //       }
                                  //     }).toList(),
                                  //   ),
                                  // )
                                ],
                              );
                            }),
                            MusicPlaylistPage(),
                            RoomMusicSearchPage(),
                          ],
                        ),
                      ),
                    ],
                  ),
                  PositionedDirectional(
                    start: 0,
                    end: 0,
                    bottom: 0,
                    child: MusicMediaBarWidget(),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // bool isShowCancel = false;

  Widget get searchBar => Container(
        alignment: AlignmentDirectional.centerStart,
        margin: const EdgeInsets.only(left: 20, right: 20, top: 9, bottom: 9),
        padding: const EdgeInsets.only(left: 20),
        width: Get.width,
        height: 40,
        decoration: const ShapeDecoration(
          shape: StadiumBorder(),
          color: Color(0xFFFAFAFA),
        ),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                focusNode: focusNode,
                controller: _textController,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.zero,
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                  ),
                  hintText: T.current!.search_singer,
                  hintStyle: TextStyle(
                    fontSize: 14,
                    color: Color(0xFFD5D5D5),
                    // color: Colors.green,
                  ),
                  labelStyle: TextStyle(
                    fontSize: 14,
                    color: Color(0xFF666666),
                  ),
                ),
                textInputAction: TextInputAction.done,
                onSubmitted: (value) {
                  centerController.showSearch(value);
                },
                onChanged: (text) {
                  if (text.isNotEmpty) {
                    centerController.cancelBtn(true);
                  } else {
                    centerController.cancelBtn(false);
                  }
                },
              ),
            ),
            GetBuilder<RoomMusicCenterController>(
              id: "is_show",
              builder: (logic) {
                if (logic.isShowCancel) {
                  return GestureDetector(
                    onTap: () {
                      _textController.clear();
                      FocusScope.of(context).unfocus();
                      centerController.dismissSearch();
                      centerController.cancelBtn(false);
                    },
                    child: Container(
                      padding: const EdgeInsets.only(
                          left: 10, top: 10, bottom: 10, right: 5),
                      child: Image.asset(
                        "assets/images/ic_cancel.png",
                        width: 10,
                        height: 10,
                        color: Color(0xFF999999),
                        fit: BoxFit.fill,
                      ),
                    ),
                  );
                } else {
                  return const SizedBox.shrink();
                }
              },
            ),
            const SizedBox(width: 16),
          ],
        ),
      );

  @override
  void dispose() {
    _disposeMusicController();
    super.dispose();
  }

  void _disposeMusicController() async {
    await centerController.savePlaylist();
    MediaPlayerState state =
        await centerController.playState(centerController.currentMusic);
    if (state != MediaPlayerState.playerStatePlaying) {
      Get.delete<RoomMusicCenterController>();
      Get.delete<RoomMusicMineController>();
    }
  }

  void _pickMusics() async {
    final mineController = Get.find<RoomMusicMineController>();
    // FilePickerResult? result = await FilePicker.platform.pickFiles(
    //   type: FileType.custom,
    //   allowMultiple: true,
    //   allowedExtensions: ['mp3', 'm4a'],
    // );

    // mineController.musicNeedUpload.addAll(result!.files
    //     .where((element) => element.path != null)
    //     .map((e) => UploadMusic(e.path!, centerController.localSongCode,
    //         name: e.name)));

    Get.to(() => const MusicUploadConfirmPage(), preventDuplicates: false);
  }
}
